﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using System.IO;
namespace TuiXin
{
    public class Sockets:AtomBase
    {
        public Socket socket;
        public string IP = "123.196.120.146";
        public int Port = 8900;
        public string key = "abcdabcdabcdabcd";
        public byte[] SBytes;
        public byte[] RBytes;
        public int Seq = 0;
        public bool Connected = false; //check socket is connected flag

        public void ConnectServer()
        {
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                this.socket.Connect(IPAddress.Parse(IP), Port);

            }
            catch (Exception err)
            {
                log.Msg("ERR_ConnectServer", "DEMO Index=" + this.Index.ToString() + " , Connect Server failure" + err.ToString());
                this.SocketClose("ConnectServer");
            }
            if (this.socket.Connected)
            {

                log.Msg("ConnectServer", this.Index.ToString() + "  , Connect Server");

                this.Connected = true;
                Thread recThread = new Thread(new ThreadStart(this.Receive));
                recThread.Start();
            }
            else
            {
                log.Msg("ERR_ConnectServer", this.Index.ToString() + "Connect Server failure");
                this.SocketClose("ConnectServer");
            }
        }
        public void SocketClose(string Msg)
        {
            //log.Msg("SocketClose", "Socket Index=" + this.Index.ToString() + "," + Msg);
            //this.IsLogin = false;
            this.Connected = false;
            this.socket.Shutdown(SocketShutdown.Both);
            this.socket.Close();

            if (!Msg.Equals("END"))
            {
                Thread.Sleep(2000);
                this.ConnectServer();
            }
        }
        #region Recieve
        public void Receive()
            { 
               while (this.Connected)
                {
                    try
                    {
                        byte[] buf = new byte[this.socket.Available];
                        
                        //this.socket.Receive(buf);
                        if(this.socket.Available>0)
                        {
                            this.socket.Receive(buf, this.socket.Available, SocketFlags.None);
                            //this.socket.Receive(buf, Seq, this.socket.Available - Seq, SocketFlags.None);
                           // Seq = Seq + this.socket.Available;
                            log.Bytes("Recieve", buf);
                            string s = Encoding.Default.GetString(cbc.cbc_rc4_Decrypt(buf, this.GetBytes(key)));
                            log.Msg("Recieve", s);
                            IMSG.Do(s); 
                        }
                        else
                        {
                            Thread.Sleep(100);
                        }
                        //log.Msg("Recieve", this.socket.Available.ToString());
                        //此处对buf进行操作
                        // Do(buf)
                        ////////////////////
                        
                    }
                    catch (SocketException err)
                    {
                        log.Msg("ERR_Receive_SocketException", err.ToString());
                    } 

                }
             }
        #endregion

        public void SendBytes(byte[] sendbytes)
        {
            int sent = 0;
            if (this.socket.Connected)
            {
                lock (this.socket)
                {
                    try
                    {
                        sent = this.socket.Send(sendbytes);
                        log.Bytes("SendBytes", sendbytes);
                    }
                    catch (Exception err)
                    {
                        this.SocketClose("SendBytes");
                        log.Msg("Err_SendBytes", err.ToString());
                    }
                }
                //sent = this.socket.Send(sendbytes);
                //log.Bytes("SendBytes", sendbytes);
            }
        }
 
        public byte[] GetBytes(string s)   //返回当前对象的字节数组
        {
            byte[] reVal = Encoding.Default.GetBytes(s);
            
            return (reVal);
        }
        public byte[] HexStringToByte(string skey) //hexstring to byte[]
        {
            byte[] test = new byte[skey.Length / 2];
            for (int l = 0; l < skey.Length; l = l + 2)
            {
                try
                {
                    test[l / 2] = byte.Parse(skey.Substring(l, 2), System.Globalization.NumberStyles.HexNumber);
                }
                catch (Exception errParse)
                {
                    return null;
                }
            }
            return test;
        }

    }
}
